#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from typing import Optional

# 创建路由
router = APIRouter(tags=["views"])

# 获取日志记录器
logger = logging.getLogger(__name__)

# 配置模板
templates = Jinja2Templates(directory="templates")

@router.get("/", response_class=HTMLResponse)
async def index(request: Request):
    """首页
    
    Args:
        request: 请求对象
        
    Returns:
        HTMLResponse: HTML响应
    """
    return templates.TemplateResponse("index.html", {"request": request})

@router.get("/viewer/{filename}", response_class=HTMLResponse)
async def viewer(request: Request, filename: str):
    """知识片段编辑器页面
    
    Args:
        request: 请求对象
        filename: 文件名
        
    Returns:
        HTMLResponse: HTML响应
    """
    return templates.TemplateResponse("viewer.html", {"request": request, "filename": filename})

@router.get("/get_qa_file/{filename}")
async def get_qa_file(filename: str):
    """获取知识问答对文件
    
    Args:
        filename: 文件名
        
    Returns:
        FileResponse: 文件响应
    """
    file_path = os.path.join("output", filename)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="找不到指定的文件")
    
    return FileResponse(file_path)

@router.get("/api/system/cleanup")
async def cleanup_files(request: Request, max_age_minutes: Optional[int] = None):
    """手动触发文件清理操作
    
    Args:
        max_age_minutes: 可选参数，指定清理超过多少分钟的文件（临时覆盖配置）
        
    Returns:
        清理结果统计
    """
    try:
        # 获取文件清理服务
        file_cleaner = request.app.state.file_cleaner
        if not file_cleaner:
            return JSONResponse(
                status_code=500,
                content={"error": "文件清理服务未初始化"}
            )
        
        # 执行清理
        result = await file_cleaner.manual_cleanup(max_age_minutes)
        
        return result
    except Exception as e:
        logger.error(f"手动清理文件失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={"error": f"清理文件失败: {str(e)}"}
        ) 